const path = require("path");
const webpack = require("webpack");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const PreloadWebpackPlugin = require("preload-webpack-plugin");
const CssUrlRelativePlugin = require("css-url-relative-plugin");
const HttpPushWebpackPlugin = require("http-push-webpack-plugin");
const ExtractTextPlugin = require('extract-text-webpack-plugin')
// const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const autoprefixer = require('autoprefixer');
const keyName = process.env.npm_lifecycle_event;

const glob = require("glob");

const IS_DEV = process.env.NODE_ENV === "dev";

const plugins = [
  new CleanWebpackPlugin(),
  new webpack.ProvidePlugin({
    $http: "axios",
    $: "jquery",
    jQuery: "jquery",
    "windows.jQuery": "jquery"
  }),
  new CopyWebpackPlugin([
    {
      from: "./src/public",
      to: "public"
    }
  ]),
  new MiniCssExtractPlugin({
    filename: IS_DEV ? "css/[name].css" : "css/[name].[contenthash].css",
    chunkFilename: "css/[id].css"
  }),
  new webpack.HashedModuleIdsPlugin(),
  new PreloadWebpackPlugin({
    include: "initial"
  }),
  new CssUrlRelativePlugin()
];
let publicPath = "";

if (keyName === "push") {
  (publicPath = "/public/siweiguo/"),
    plugins.push(
      new HttpPushWebpackPlugin({
        receiver: "http://forsomething.cn:8990/receiver", // 服务端文件上传接口
        token: "123token", // 验证token
        to: "/home/node-server/myCms/public/siweiguo" // 上传文件目录h5Sdkzxxtest
      })
    );
}
if (keyName === "build") {
  // (publicPath = "/public/siweiguo/"),
  //   plugins.push(
  //     new HttpPushWebpackPlugin({
  //       receiver: "http://forsomething.cn:8990/receiver", // 服务端文件上传接口
  //       token: "123token", // 验证token
  //       to: "/home/node-server/myCms/public/siweiguo" // 上传文件目录h5Sdkzxxtest
  //     })
  //   );
}

const config = {
  mode: IS_DEV ? "development" : "production",
  devtool: IS_DEV ? "eval" : "source-map",
  // entry: "./src/js/index.js",
  output: {
    filename: "js/[name].[hash].js",
    path: path.resolve(__dirname, "dist"),
    publicPath: publicPath
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel-loader"
      },
      {
        test: /\.scss$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it use publicPath in webpackOptions.output
              publicPath: '../'
            }
          },
          'css-loader',
          'postcss-loader',
          'sass-loader',
        ]
      },
      {
        test: /\.(gif|png|jpe?g|svg)$/i,
        use: [
          {
            loader: "url-loader",
            options: {
              limit: 8192,
              name: "[name]-[hash].[ext]",
              fallback: "file-loader",
              outputPath: "imgs"
            }
          }
        ]
      }
    ]
  },
  plugins: plugins,
  devServer: {
    contentBase: path.join(__dirname, "src")
  },
  optimization: {
    runtimeChunk: "single",
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /node_modules/,
          chunks: "initial",
          name: "vendor",
          priority: 10,
          enforce: true
        }
      }
    },
    minimizer: []
  },
  resolve: {
    alias: {
      "@": require("path").resolve(__dirname, "src")
    }
  }
};

if (!IS_DEV) {
  const TerserPlugin = require("terser-webpack-plugin");
  const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");

  config.optimization.minimizer.push(
    new TerserPlugin(),
    new OptimizeCSSAssetsPlugin({})
  );
}

const files = glob.sync("./src/pages/**/*.html");
const entry = {};
files.forEach(file => {
  let _fileName = file.split("pages/")[1];
  let extname = path.extname(file);
  let result = _fileName.substring(0, _fileName.indexOf(extname));
  entry[result] = path.resolve(__dirname, `./src/js/${result}.js`);
  config.plugins.push(
    new HtmlWebPackPlugin({
      filename: path.basename(file),
      template: file,
      chunks: [result],
      favicon: path.resolve(__dirname, "./src/public/favicon32.png"),
      minify: !IS_DEV
    })
  );
});
config.entry = entry;

module.exports = config;
